#!/usr/bin/env python
# -*- coding: utf-8 -*-
#### Copyright (c) 2008 Clóvis Fabrício Costa - All rights reserved

import os
from pysh.cmd import c

class PathCmd(object):
    def __init__(self, pathobj, startingcmd=c):
        self._pysh_path = pathobj
        self._pysh_cmd = startingcmd

    def __getattr__(self, attr):
        if attr.startswith('_pysh_'):
            return super(PathCmd, self).__getattr__(self, attr)
        else:
            return PathCmd(self._pysh_path, 
                           getattr(self._pysh_cmd, attr))

    def __getitem__(self, item):
        return PathCmd(self._pysh_path, self._pysh_cmd[item])

    def __call__(self, *args, **kwds):
        return self._pysh_cmd(str(self._pysh_path), *args, **kwds)

    def __repr__(self):
        return '<%r(%r)>' % (self._pysh_cmd, self._pysh_path)


class Path(object):
    def __init__(self, starting_path):
        self._pysh_path = os.path.realpath(str(starting_path))

    def __getattr__(self, attr):
        if attr.startswith('_pysh_'):
            return super(Path, self).__getattr__(self, attr)
        elif attr == '_':
            attr = os.path.pardir
        return self[attr]

    def __getitem__(self, item):
        return Path(os.path.join(str(self), item))

    def __iter__(self):
        this = self(os)
        if this.path.isdir():
            return (Path(os.path.join(str(self), path)) for path in this.listdir())
        else:
            return self(open)()

    def __call__(self, *args, **kwds):
        return PathCmd(self, *args, **kwds)

    def __str__(self):
        return self._pysh_path

    def __repr__(self):
        mypath = self(os.path)
        if mypath.exists():
            if mypath.isdir():
                info = '(dir)'
            else:
                info = mypath.getsize()
            return 'Path(%r)<%s>' % (str(self), info)
        else:
            return 'Path(%r)' % (str(self),)


class CurDir(Path):
    def __init__(self, starting_path=None):
        if starting_path is not None:
            os.chdir(starting_path)

    @property
    def _pysh_path(self):
        return os.getcwd()

    def __repr__(self):
        return 'CurDir(%r)' % str(self)


if __name__ == '__main__':
    p = root = Path('/')
    cd = CurDir()
    
